Having a variable with the same name in two unrelated classes is fine, but do the same thing within a class hierarchy and you’ll get confusion at
best, chaos at worst.
Noncompliant code example
class Fruit {
protected:
Season ripe;
static Color flesh;
// ...
};
class Raspberry : public Fruit {
private:
bool ripe; // Noncompliant
static Color FLESH; // Noncompliant
};
Compliant solution
class Fruit {
protected:
Season ripe;
static Color flesh;
// ...
};
class Raspberry : public Fruit {
private:
bool ripened;
static Color FLESH_COLOR;
};
Exceptions
This rule ignores same-name fields that are static
in both the parent and child classes. This rule ignores private
parent
class fields, but in all other such cases, the child class field should be renamed.
class Fruit {
private:
Season ripe;
// ...
};
class Raspberry : public Fruit {
private:
Season ripe; // Compliant as parent field 'ripe' is anyway not visible from Raspberry
// ...
};
or
class Fruit {
public:
Season ripe;
// ...
};
class RedFruit : private Fruit {
};
class Raspberry : public RedFruit { // RedFruit inherits from Fruit privately
private:
Season ripe; // Compliant as parent field 'ripe' is anyway not visible from Raspberry
// ...
};